package com.epfresh.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.adapter.StoreGridAdapter;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.*;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.widget.list.LoadMoreListView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.api.widget.ptr.PtrMdFrameLayout;
import com.epfresh.bean.ContentEntity;
import com.epfresh.bean.ListStore;
import com.epfresh.global.BaseActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SearchStoreActivity extends BaseActivity implements LoadMoreListView.IXListViewListener{
    private LoadMoreListView mListView;
    private RelativeLayout nodate_ll;
    private TextView nodate_hint;
    private TextView nodate_start;
    private ImageView nodate_img;
    //    private ArrayList<ListStore> mDataList;
    //private ArrayList<ListStore> list;
    private ArrayList<ArrayList<ListStore>> newList = new ArrayList<>();
    Context mContext;
    int page=0; //加载页码控制 从0开始
    StoreGridAdapter adapter;

    String favorite="";
    String marketId="",areaId="";

    String searchKey;


    boolean firstFlag = true;

    private View vSearch;


    private TextView tvSearch;
    private TextView tvContent;
    @Override
    protected View getToolBar() {
        View actionbar = this.inflaterView(R.layout.toolbar_search_result, null);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(-1, this.getResources().getDimensionPixelSize(com.epfresh.api.R.dimen.action_bar_height));
        actionbar.setLayoutParams(lp);
        this.toolbarTitle = (TextView) actionbar.findViewById(R.id.toolbar_title);

        this.ivBack = (ImageView) actionbar.findViewById(R.id.iv_back);

        this.ivBack.setOnClickListener(this);

        return actionbar;
    }


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        searchKey = getIntent().getStringExtra("searchKey");
        initView();
        mListView = (LoadMoreListView) findViewById(R.id.listview);
        mListView.setPullLoadEnable(false); // 设置可滑动
        mListView.setXListViewListener(this);// 设置滑动监听器
        mContext = this;
        adapter = new StoreGridAdapter(this, newList);
        mListView.setAdapter(adapter);
        adapter.setOnItemClickListener(this);
        nodate_hint.setText("暂无店铺！");
        initHeadView();
        refresh();
    }

    void initView(){
        setContentView(R.layout.activity_list);
        mListView = (LoadMoreListView)findViewById(R.id.listview);
        nodate_hint = (TextView)findViewById(R.id.nodate_hint);
        nodate_ll = (RelativeLayout)findViewById(R.id.nodate_ll);
        nodate_start = (TextView)findViewById(R.id.nodate_start);
        vSearch = findViewById(R.id.ll_search);
        tvSearch = (TextView) findViewById(R.id.tv_search);
        tvContent = (TextView) findViewById(R.id.et_content);
        tvContent.setText(searchKey);
        tvSearch.setOnClickListener(this);
        vSearch.setOnClickListener(this);
    }
    private PtrMdFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, mListView, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    private void initHeadView() {
        ptrFrameLayout = (PtrMdFrameLayout) findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
//        ptrFrameLayout.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                ptrFrameLayout.autoRefresh(true);
//            }
//        }, 200);
    }

    public void refresh() {
        if (mListView != null) {
            mListView.resetNoMore();
        }
        expectPage = 0;
        requestOrderList(0);
    }

    @Override
    public void onLoadMore() {
        if (mLastFlag) {
            mListView.stopLoadMoreNoMore();
        } else {
            expectPage = currentPage + 1;
            requestOrderList(expectPage);
        }
    }

    boolean mLastFlag = false;
    //当前分页
    private int currentPage = 0;
    //期望的分页
    private int expectPage = 0;
    private RequestTag requestTag = new RequestTag();

    public void requestOrderList(int page) {

/*        SharedPreferences user = getSharedPreferences(
                Constant.USERINFO, Activity.MODE_PRIVATE);*/
        RequestEntityPurchase<Map<String, Object>> entity = new RequestEntityPurchase<>();
        Map<String, Object> map = new HashMap<>();
        map.put("name",searchKey);
        map.put("marketId", marketId);
        map.put("areaId", areaId);
        map.put("favorite",favorite);
        map.put("pageNumber", page + "");
        map.put("pageSize", 10 + "");
        map.put("sortProperty", "name");
        map.put("sortDirection", "DESC");
        entity.setCmd(AppPurchaseRouterConstant.cmd_store_store_list);
        entity.setParameters(map);
        requestTag.tag = AppPurchaseRouterConstant.cmd_store_store_list;
        requestTag.action = page;
        request(entity, requestTag, onRequestListener);

    }

    OnRequestListener<ContentEntity<ListStore>> onRequestListener = new OnRequestListener<ContentEntity<ListStore>>() {
        @Override
        public ContentEntity<ListStore> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<ContentEntity<ListStore>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            updateView(tag);
            switch (failCode) {
                case HttpRequest.FAIL_NOT_FOUND:
                    showExceptionView(0, null, 0);
                    break;
                case HttpRequest.FAIL_NO_NET:
                    showExceptionView(0, null, 0);
                    break;
                case HttpRequest.FAIL_NET_FAULT:
                    showExceptionView(0, null, 0);
                default:
                    showExceptionView(0, null, 0);
                    //showReload();
                    break;
            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            updateView(tag);
            showMainView();
        }

        @Override
        public void onStart(Object tag) {
            if(firstFlag==true){
                firstFlag = false;
                showProgressDialog();
            }
            nodate_ll.setVisibility(View.GONE);
            mListView.setVisibility(View.VISIBLE);
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<ListStore>> response, Object tag) {
            hideProgressDialog();
            showMainView();
            ContentEntity<ListStore> goodsResponse = response.getResponseElement();
            List<ListStore> content = goodsResponse.getContent();
            currentPage = goodsResponse.getNumber();
            mLastFlag = goodsResponse.getLast();
            boolean isRefresh = updateView(tag);
            if (content != null && content.size() > 0) {
                if (isRefresh) {
                    newList.clear();
                    mListView.setPullLoadEnable(true);
                    if (mLastFlag) {
                        mListView.noMore();
                    }
                }

                ArrayList<ArrayList<ListStore>> newFlag = new ArrayList<>();//(content.size()+1)/2);
                for(int i=0;i<(content.size()+1)/2;i++){
                    ArrayList<ListStore> flag = new ArrayList<>();
                    flag.add(content.get(2*i));
                    if (content.size() > 2 * i + 1) {
                        flag.add(content.get(2 * i + 1));
                    }
                    newFlag.add(flag);
                    Log.e("flagList____size",""+newFlag.size());

                }
                newList.addAll(newFlag);
                Log.e("newList____size",""+newList.size());
                adapter.notifyDataSetChanged();

/*                list.addAll(content);
                adapter.notifyDataSetChanged();*/




            } else {
                nodate_ll.setVisibility(View.VISIBLE);
                mListView.setVisibility(View.GONE);
                //没有数据
                if (isRefresh) {
                    newList.clear();
                }
            }


        }
    };

    private boolean updateView(Object tag) {
        if (tag != null) {
            RequestTag requestTag = (RequestTag) tag;
            if (requestTag.action == 0) {
                ptrFrameLayout.refreshComplete();
                return true;
            } else {
                if (mLastFlag) {
                    mListView.stopLoadMoreNoMore();
                } else {
                    mListView.stopLoadMore();
                }
            }
        } else {
            ptrFrameLayout.refreshComplete();
            if (mLastFlag) {
                mListView.stopLoadMoreNoMore();
            } else {
                mListView.stopLoadMore();
            }
        }
        return false;
    }


    public void onClick(View v) {
        int position;
        switch (v.getId()) {
            case R.id.tv_search:
            case R.id.ll_search:
                search();
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.baseback:
                // 返回上一页
                finish();
                break;
            case R.id.nodate_start:

//                refresh();
                break;
            case R.id.iv_phone:
                position = (Integer)v.getTag(R.id.item_key_position);

                Intent call = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + newList.get(position/10).get(position%10).getManagerPhone()));//调出来拨打页面；
                startActivity(call);
                break;
            case R.id.v_1:
            case R.id.v_2:
                position = (Integer)v.getTag(R.id.item_key_position);
                Intent storeIntent = new Intent(this,
                        CommonStoreActivity.class);
                storeIntent.putExtra("storeId", newList.get(position/10).get(position%10).getId());
                startActivity(storeIntent);
                break;


        }
    }

    private void search() {

        Intent intent = new Intent(this, SearchActivity.class);
        startActivity(intent);
        finish();
    }

/*
    class StoresAdapter extends CommonAdapter<ArrayList<ListStore>> implements View.OnClickListener{

        public StoresAdapter(Context context, ArrayList<ArrayList<ListStore>> runPacks, int a) {
            super(context, runPacks, a);
        }
        @Override
        public void onClick(View v){
            Object tag = v.getTag(R.id.item_key_position);
            int position = (int) tag;
            switch (v.getId()) {
                case R.id.rl_center:
                    Intent storeIntent = new Intent(mContext,
                            CommonStoreActivity.class);
                    storeIntent.putExtra("storeId", list.get(position).getId());
                    startActivity(storeIntent);
                    break;
                case R.id.tv_call:
                    Intent call = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + list.get(position).getManagerPhone()));//调出来拨打页面；
                    startActivity(call);
                    break;
            }
        }

        @Override
        public void convert(final ViewHolder holder, final ArrayList<ListStore> bean) {
            holder.setText(R.id.tv_center_name, bean.getName());
            holder.setText(R.id.tv_detail, bean.getDescription());
            ImageLoader.getInstance().displayImage(bean.getLogoUrl(), (ImageView) holder.getView(R.id.iv_center));
            holder.getView(R.id.rl_center).setTag(R.id.item_key_position, list.indexOf(bean));
            holder.getView(R.id.tv_call).setTag(R.id.item_key_position, list.indexOf(bean));
            holder.setOnClickListener(R.id.rl_center, this);
            holder.setOnClickListener(R.id.tv_call, this);
            if(bean.getStall()==null||"".equals(bean.getStall())){
                holder.getView(R.id.tv_address_number).setVisibility(View.GONE);
            }else {
                holder.getView(R.id.tv_address_number).setVisibility(View.VISIBLE);
                holder.setText(R.id.tv_address_number, bean.getStall());
            }
            holder.setText(R.id.tv_time, bean.getBusinessTime());
            holder.setText(R.id.tv_number, bean.getOnShelvesProductCount()+"件商品");
            holder.setText(R.id.tv_evaluate, "好评"+bean.getGoodCommentsRate());
            ImageView ivFlag = (ImageView)holder.getView(R.id.iv_flag);
            ivFlag.setVisibility(View.GONE);
            if(bean.getIsAcceptOrders()!=null&&bean.getIsAcceptOrders()==1){
                if(bean.getRecType()!=null&&bean.getRecType()==1){
                    ivFlag.setVisibility(View.VISIBLE);
                    ivFlag.setImageResource(R.mipmap.store_recent_triangle);
                }else if(bean.getRecType()!=null&&bean.getRecType()==2) {
                    ivFlag.setVisibility(View.VISIBLE);
                    ivFlag.setImageResource(R.mipmap.store_concern_triangle);
                }
            }else{
                ivFlag.setVisibility(View.VISIBLE);
                ivFlag.setImageResource(R.mipmap.store_sleep_triangle);
            }

        }
    }*/
}
